<template>
  <div>

    <div class="container">
      <div class="handle-box">

        <el-input v-model="query.name" placeholder="用户名" clearable class="handle-input mr10"></el-input>
          <el-select
            class="handle-input mr10"
            v-model="query.conferenceId"
            placeholder="请选择会议名称"
            filterable
            clearable
          >
            <el-option
              v-for="conf in conferenceData"
              :key="conf.conferenceId"
              :label="conf.conferenceName"
              :value="conf.conferenceId"
            />
          </el-select>
        <el-select v-model="query.address"  placeholder="省份" class="handle-select mr10" filterable clearable>
          <el-option key="1" label="北京市" value="北京市"></el-option>
          <el-option key="2" label="天津市" value="天津市"></el-option>
          <el-option key="3" label="上海市" value="上海市"></el-option>
          <el-option key="4" label="重庆市" value="重庆市"></el-option>
          <el-option key="5" label="河北省" value="河北省"></el-option>
          <el-option key="6" label="山西省" value="山西省"></el-option>
          <el-option key="7" label="辽宁省" value="辽宁省"></el-option>
          <el-option key="8" label="吉林省" value="吉林省"></el-option>
          <el-option key="9" label="黑龙江省" value="黑龙江省"></el-option>
          <el-option key="10" label="江苏省" value="江苏省"></el-option>
          <el-option key="11" label="浙江省" value="浙江省"></el-option>
          <el-option key="12" label="安徽省" value="安徽省"></el-option>
          <el-option key="13" label="福建省" value="福建省"></el-option>
          <el-option key="14" label="江西省" value="江西省"></el-option>
          <el-option key="15" label="山东省" value="山东省"></el-option>
          <el-option key="16" label="河南省" value="河南省"></el-option>
          <el-option key="17" label="湖北省" value="湖北省"></el-option>
          <el-option key="18" label="湖南省" value="湖南省"></el-option>
          <el-option key="19" label="广东省" value="广东省"></el-option>
          <el-option key="20" label="海南省" value="海南省"></el-option>
          <el-option key="21" label="四川省" value="四川省"></el-option>
          <el-option key="22" label="贵州省" value="贵州省"></el-option>
          <el-option key="23" label="云南省" value="云南省"></el-option>
          <el-option key="24" label="陕西省" value="陕西省"></el-option>
          <el-option key="25" label="甘肃省" value="甘肃省"></el-option>
          <el-option key="26" label="青海省" value="青海省"></el-option>
          <el-option key="27" label="台湾省" value="台湾省"></el-option>
          <el-option key="28" label="内蒙古自治区" value="内蒙古自治区"></el-option>
          <el-option key="29" label="广西壮族自治区" value="广西壮族自治区"></el-option>
          <el-option key="30" label="西藏自治区" value="西藏自治区"></el-option>
          <el-option key="31" label="宁夏回族自治区" value="宁夏回族自治区"></el-option>
          <el-option key="32" label="新疆维吾尔自治区" value="新疆维吾尔自治区"></el-option>
          <el-option key="33" label="香港特别行政区" value="香港特别行政区"></el-option>
          <el-option el-option key="34" label="澳门特别行政区" value="澳门特别行政区"></el-option>
        </el-select>
        <el-input v-model="query.arriveLocatoin" placeholder="到达地点" clearable class="handle-input mr10"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>

        <!-- ✅ 导入导出按钮 -->
        <!-- <el-button
          v-if="$store.state.user && $store.state.user.role === 'ROLE_SUPER_ADMIN'"
          type="success"
          icon="el-icon-upload2"
          class="mr10"
          @click="$refs.excelInput.click()"
        >导入 Excel</el-button> -->
        <input
          type="file"
          ref="excelInput"
          style="display: none"
          accept=".xlsx, .xls"
          @change="importFromExcel"
        />
        <el-button
          v-if="$store.state.user && ($store.state.user.role === 'ROLE_SUPER_ADMIN')"
          type="warning"
          icon="el-icon-download"
          @click="handleExport"
        >导出 Excel</el-button>
      </div>

      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        
      >
        <!-- <el-table-column prop="participantId" label="标识"></el-table-column> -->
        <el-table-column prop="fullName" label="姓名" width="80px"></el-table-column>
        <el-table-column prop="gender" label="性别" width="50px">
          <template slot-scope="scope">
            <span>{{ scope.row.gender === 1 ? '女' : '男' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="typeId"
          label="人员类型"
          :formatter="formatUserType">
        </el-table-column>
        <el-table-column prop="conferences.conferenceName" label="所属会议"></el-table-column>
        <el-table-column prop="affiliation" label="所属学校"></el-table-column>
        <el-table-column prop="phoneNumber" label="手机号"></el-table-column>
        <el-table-column prop="idCardNumber" label="身份证号"></el-table-column>
        <el-table-column prop="province" label="省份"></el-table-column>
        <el-table-column prop="transportType" label="交通类型" :formatter="formatTransportType"></el-table-column>
        <el-table-column prop="flightTrainNumber" label="航班/车次号"></el-table-column>
        <el-table-column prop="arrivalTime" label="到达时间" width="180px" :formatter="formatDateTime"></el-table-column>
        <el-table-column prop="arrivalLocation" label="到站地点"></el-table-column>
        <el-table-column
          prop="hasPaidConferenceFee"
          label="是否缴费"
          :formatter="(row) => row.hasPaidConferenceFee === 1 ? '是' : '否'">
        </el-table-column>

        <el-table-column
          prop="signedIn"
          label="是否签到"
          :formatter="(row) => row.signedIn === 1 ? '是' : '否'">
        </el-table-column>
        <el-table-column
          prop="signedIn"
          label="8月15日晚餐"
          :formatter="(row) => row.needsPreDinner === 1 ? '是' : '否'">
        </el-table-column>
        <el-table-column
          prop="signedIn"
          label="8月16日中餐"
          :formatter="(row) => row.needsLunch === 1 ? '是' : '否'">
        </el-table-column>
          <el-table-column
          prop="signedIn"
          label="8月16日晚餐"
          :formatter="(row) => row.needsDinner === 1 ? '是' : '否'">
        </el-table-column>
        <el-table-column prop="notes" label="备注"></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <div v-if="$store.state.user && ($store.state.user.role === 'ROLE_SUPER_ADMIN' || $store.state.user.role === 'ROLE_TOLL_ADMIN')">
              <el-button
                type="text"
                icon="el-icon-edit"
                @click="handleEdit(scope.row)"
              >编辑</el-button>
            </div>
            <div v-if="$store.state.user && ($store.state.user.role === 'ROLE_LODGING_ADMIN' || $store.state.user.role === 'ROLE_SUPER_ADMIN')">
              <el-button
                type="text"
                icon="el-icon-edit"
                @click="handleEditLodging(scope.row)"
              >住宿安排</el-button>
            </div>
            <div v-if="$store.state.user && ($store.state.user.role === 'ROLE_TRAVEL_ADMIN' || $store.state.user.role === 'ROLE_SUPER_ADMIN')">
              <el-button
                type="text"
                icon="el-icon-edit"
                @click="handleEditTravel(scope.row)"
              >车辆分配</el-button>
            </div>
            <!--
            <div>
              <el-button
                type="text"
                icon="el-icon-delete"
                class="red"
                @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button>
            </div>
            -->
          </template>
        </el-table-column>

      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
      <el-form ref="form" :model="form" label-width="70px">

        <el-form-item label="是否缴费">
          <el-radio-group v-model="form.hasPaidConferenceFee">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      
        <el-form-item label="是否签到">
          <el-radio-group v-model="form.signedIn">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            type="textarea"
            v-model="form.notes"
            :autosize="{ minRows: 3, maxRows: 6 }"
            placeholder="请输入备注内容"
            resize="vertical"
          />
        </el-form-item>
      
      </el-form>
    
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 住宿分配弹出框 -->
    <el-dialog title="住宿安排" :visible.sync="editLodgingVisible" width="80%">
      <div style="display: flex; gap: 20px;">
        <!-- 左侧表单区域 -->
        <div style="flex: 1; min-width: 300px;">
          <h4 style="margin-top: 0; margin-bottom: 20px; color: #409EFF;">新增住宿安排</h4>
          <el-form
            ref="lodgingForm"
            :model="lodgingForm"
            :rules="rules"
            label-width="90px"
          >
            <el-form-item label="酒店名称" prop="hotelId">
              <el-select
                v-model="lodgingForm.hotelId"
                placeholder="请选择酒店名称"
                filterable
                clearable
                style="width: 100%;"
              >
                <el-option
                  v-for="hotel in hotels"
                  :key="hotel.hotelId"
                  :label="hotel.hotelName"
                  :value="hotel.hotelId"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="用户姓名" prop="fullName">
              <el-input v-model="lodgingForm.participantId" v-show="false"/>
              <el-input v-model="lodgingForm.fullName" disabled/>
            </el-form-item>
            
            <el-form-item label="房间号" prop="roomNumber">
              <el-input v-model="lodgingForm.roomNumber" placeholder="请输入房间号" />
            </el-form-item>
          
            <el-form-item label="入住日期" prop="checkInDate">
              <el-date-picker
                v-model="lodgingForm.checkInDate"
                type="datetime"
                placeholder="请选择入住日期"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%;"
              />
            </el-form-item>

            <el-form-item label="退房日期" prop="checkOutDate">
              <el-date-picker
                v-model="lodgingForm.checkOutDate"
                type="datetime"
                placeholder="请选择退房日期"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%;"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="saveEditLogding">保存住宿安排</el-button>
              <el-button @click="resetLodgingForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 右侧表格区域 -->
        <div style="flex: 2; min-width: 450px;">
          <div style="background: #f8f9fa; padding: 16px; border-radius: 8px; height: 500px; display: flex; flex-direction: column;">
            <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px;">
              <h4 style="margin: 0; color: #409EFF; font-size: 16px;">
                <i class="el-icon-s-home" style="margin-right: 8px;"></i>
                当前住宿记录
              </h4>
              <el-tag v-if="userLodgingRecords && userLodgingRecords.length > 0" 
                      type="info" size="small">
                共 {{ userLodgingRecords.length }} 条记录
              </el-tag>
            </div>
            
            <!-- 表格容器 -->
            <div style="flex: 1; background: white; border-radius: 6px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
              <el-table
                v-if="userLodgingRecords && userLodgingRecords.length > 0"
                :data="userLodgingRecords"
                style="width: 100%; height: 100%;"
                size="small"
                stripe
                :header-cell-style="{ background: '#fafafa', color: '#606266', fontSize: '13px' }"
              >
                <el-table-column 
                  prop="hotelName" 
                  label="酒店名称" 
                  min-width="100"
                  show-overflow-tooltip>
                  <template slot-scope="scope">
                    <div style="display: flex; align-items: center;">
                      <i class="el-icon-office-building" style="color: #409EFF; margin-right: 6px;"></i>
                      <span>{{ scope.row.hotels.hotelName || '未知酒店' }}</span>
                    </div>
                  </template>
                </el-table-column>
                
                <el-table-column 
                  prop="roomNumber" 
                  label="房间号" 
                  width="80"
                  align="center">
                  <template slot-scope="scope">
                    <el-tag size="mini" type="success">{{ scope.row.roomNumber }}</el-tag>
                  </template>
                </el-table-column>
                
                <el-table-column 
                  prop="checkInDate" 
                  label="入住时间" 
                  min-width="110"
                  :formatter="formatDateTime">
                  <template slot-scope="scope">
                    <div style="font-size: 12px;">
                      <div style="color: #606266;">{{ formatDate(scope.row.checkInDate) }}</div>
                      <div style="color: #909399;">{{ formatTime(scope.row.checkInDate) }}</div>
                    </div>
                  </template>
                </el-table-column>
                
                <el-table-column 
                  prop="checkOutDate" 
                  label="退房时间" 
                  min-width="110"
                  :formatter="formatDateTime">
                  <template slot-scope="scope">
                    <div style="font-size: 12px;">
                      <div style="color: #606266;">{{ formatDate(scope.row.checkOutDate) }}</div>
                      <div style="color: #909399;">{{ formatTime(scope.row.checkOutDate) }}</div>
                    </div>
                  </template>
                </el-table-column>
                
                <el-table-column label="操作" width="80" align="center" fixed="right">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      size="mini"
                      @click="deleteLodgingRecord(scope.row)"
                      style="color: #F56C6C;"
                      icon="el-icon-delete"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              
              <!-- 空状态提示 -->
              <div v-else 
                   style="height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; color: #909399;">
                <div style="text-align: center;">
                  <i class="el-icon-s-home" style="font-size: 64px; color: #ddd; margin-bottom: 16px;"></i>
                  <p style="margin: 0; font-size: 14px; color: #909399;">暂无住宿记录</p>
                  <p style="margin: 8px 0 0 0; font-size: 12px; color: #c0c4cc;">请在左侧添加住宿安排</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelEditLogding">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 导出弹出框 -->
    <el-dialog title="导出" :visible.sync="exportVisible" width="30%">
      <el-form :model="form" :rules="rules" label-width="70px" ref="exportForm">
        <el-form-item label="会议名称" prop="conferenceId">
          <el-select
            v-model="form.conferenceId"
            filterable
            placeholder="请选择需要导出的参加某场会议的全部人员"
            style="width: 100%;">
            <el-option
              v-for="item in conferenceData"
              :key="item.conferenceId"
              :label="item.conferenceName"
              :value="item.conferenceId" />
          </el-select>
        </el-form-item>
      </el-form>
    
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelExport">取 消</el-button>
        <el-button type="primary" @click="saveExport">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 车辆分配弹出框 -->
    <el-dialog title="车辆分配" :visible.sync="editTravelVisible" width="80%">
      <div style="display: flex; gap: 20px;">
        <!-- 左侧表单区域 -->
        <div style="flex: 1; min-width: 300px;">
          <h4 style="margin-top: 0; margin-bottom: 20px; color: #409EFF;">新增车辆分配</h4>
          <el-form
            ref="travelForm"
            :model="travelForm"
            :rules="rules"
            label-width="90px"
          >
            <el-form-item label="用户姓名" prop="fullName">
              <el-input v-model="travelForm.participantId" v-show="false"/>
              <el-input v-model="travelForm.fullName" disabled/>
            </el-form-item>
            
            <el-form-item label="会议名称" prop="conferenceId">
              <el-select
                v-model="travelForm.conferenceId"
                placeholder="请选择会议名称"
                filterable
                clearable
                style="width: 100%;"
              >
                <el-option
                  v-for="conf in conferenceData"
                  :key="conf.conferenceId"
                  :label="conf.conferenceName"
                  :value="conf.conferenceId"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="车牌号" prop="vehicleId">
              <el-select
                v-model="travelForm.vehicleId"
                placeholder="请选择车辆"
                filterable
                clearable
                style="width: 100%;"
              >
                <el-option
                  v-for="car in vehicles"
                  :key="car.vehicleId"
                  :label="car.licensePlate"
                  :value="car.vehicleId"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="分配类型" prop="assignmentType">
              <el-select
                v-model="travelForm.assignmentType"
                placeholder="请选择分配类型"
                clearable
                style="width: 100%;"
              >
                <el-option :label="'接站'" :value="0" />
                <el-option :label="'会议期间'" :value="1" />
                <el-option :label="'送站'" :value="2" />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="saveEditTraval">保存车辆分配</el-button>
              <el-button @click="resetTravelForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 右侧表格区域 -->
        <div style="flex: 2; min-width: 450px;">
          <div style="background: #f8f9fa; padding: 16px; border-radius: 8px; height: 500px; display: flex; flex-direction: column;">
            <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px;">
              <h4 style="margin: 0; color: #409EFF; font-size: 16px;">
                <i class="el-icon-truck" style="margin-right: 8px;"></i>
                当前车辆分配记录
              </h4>
              <el-tag v-if="userTravelRecords && userTravelRecords.length > 0" 
                      type="info" size="small">
                共 {{ userTravelRecords.length }} 条记录
              </el-tag>
            </div>
            
            <!-- 表格容器 -->
            <div style="flex: 1; background: white; border-radius: 6px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
              <el-table
                v-if="userTravelRecords && userTravelRecords.length > 0"
                :data="userTravelRecords"
                style="width: 100%; height: 100%;"
                size="small"
                stripe
                :header-cell-style="{ background: '#fafafa', color: '#606266', fontSize: '13px' }"
              >
                <el-table-column 
                  prop="conferences.conferenceName" 
                  label="会议名称" 
                  min-width="120"
                  show-overflow-tooltip>
                  <template slot-scope="scope">
                    <div style="display: flex; align-items: center;">
                      <i class="el-icon-s-flag" style="color: #409EFF; margin-right: 6px;"></i>
                      <span>{{ scope.row.conferences && scope.row.conferences.conferenceName || '未知会议' }}</span>
                    </div>
                  </template>
                </el-table-column>
                
                <el-table-column 
                  prop="vehicles.licensePlate" 
                  label="车牌号" 
                  width="100"
                  align="center">
                  <template slot-scope="scope">
                    <el-tag size="mini" type="warning">{{ scope.row.vehicles && scope.row.vehicles.licensePlate || '未知车辆' }}</el-tag>
                  </template>
                </el-table-column>
                
                <el-table-column 
                  prop="assignmentType" 
                  label="分配类型" 
                  width="100"
                  align="center">
                  <template slot-scope="scope">
                    <el-tag 
                      size="mini" 
                      :type="scope.row.assignmentType === 0 ? 'success' : scope.row.assignmentType === 1 ? 'primary' : 'danger'">
                      {{ scope.row.assignmentType === 0 ? '接站' : scope.row.assignmentType === 1 ? '会议期间' : '送站' }}
                    </el-tag>
                  </template>
                </el-table-column>
                
                <!-- <el-table-column 
                  prop="createdAt" 
                  label="发车时间" 
                  min-width="110">
                  <template slot-scope="scope">
                    <div style="font-size: 12px;">
                      <div style="color: #606266;">{{ formatDate(scope.row.dartTime) }}</div>
                      <div style="color: #909399;">{{ formatTime(scope.row.dartTime) }}</div>
                    </div>
                  </template>
                </el-table-column> -->
                
                <el-table-column label="操作" width="80" align="center" fixed="right">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      size="mini"
                      @click="deleteTravelRecord(scope.row)"
                      style="color: #F56C6C;"
                      icon="el-icon-delete"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              
              <!-- 空状态提示 -->
              <div v-else 
                   style="height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; color: #909399;">
                <div style="text-align: center;">
                  <i class="el-icon-truck" style="font-size: 64px; color: #ddd; margin-bottom: 16px;"></i>
                  <p style="margin: 0; font-size: 14px; color: #909399;">暂无车辆分配记录</p>
                  <p style="margin: 8px 0 0 0; font-size: 12px; color: #c0c4cc;">请在左侧添加车辆分配</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelEditTravel">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as XLSX from 'xlsx';
import requests from '../utils/request'

export default {
    name: 'basetable',
    data() {
        return {
          query: {
              address: '',
              name: '',
              pageIndex: 1,
              pageSize: 100,
              conferenceId: null,
              arriveLocatoin: ''
          },
          tableData: [],
          exportData: [],
          userType: [],
          conferenceData: [],
          editVisible: false,
          editLodgingVisible: false,
          editTravelVisible: false,
          exportVisible: false,
          pageTotal: 0,
          form: {},
          idx: -1,
          id: -1,
          hotels:{},
          vehicles:{},
          form: {
            conferenceId: ''
          },
          lodgingForm:{},
          travelForm:{},
          userLodgingRecords: [], // 用户住宿记录
          userTravelRecords: [], // 用户车辆分配记录
          rules: {
            conferenceId: [
              { required: true, message: '请选择会议名称', trigger: 'change' }
            ],
            hotelId: [
              { required: true, message: '请选择酒店名称', trigger: 'change' }
            ],
            fullName: [
              { required: true, message: '请输入用户姓名', trigger: 'blur' }
            ],
            roomNumber: [
              { required: true, message: '请输入房间号', trigger: 'blur' }
            ],
            checkInDate: [
              { required: true, message: '请选择入住日期', trigger: 'change' }
            ],
            checkOutDate: [
              { required: true, message: '请选择退房日期', trigger: 'change' }
            ],
            assignmentType: [{ required: true, message: '请选择分配类型', trigger: 'change' }],
            vehicleId: [{ required: true, message: '请选择车辆', trigger: 'change' }],
          }
        };
    },
    created() {
       this.loading()
    },
    methods: {
      //加载数据
      loading() {
        requests.get("/participants/pageSelect", {
          page: this.query.pageIndex,
          size: this.query.pageSize,
          conferenceId: this.query.conferenceId,
          province: this.query.address,
          fullName: this.query.name,
          arriveLocatoin: this.query.arriveLocatoin
        }).then(res=>{
          this.pageTotal = res.length
          this.tableData = res
        });
        requests.get("/conferences/selectAll").then(res=>{
          this.conferenceData = res
        })
        requests.get("/participantTypes/selectAll").then(res=>{
          this.userType = res
        }),
        requests.get("/hotels/selectAllHotelName").then(res=>{
          this.hotels = res
        }),
        requests.get("/vehicles/selectAllVehicle").then(res=>{
          this.vehicles = res
        })
      },
      //时间格式化
      formatDateTime(row, column, cellValue) {
        if (!cellValue) return '';
        const date = new Date(cellValue);
        const pad = n => n.toString().padStart(2, '0');
        return `${date.getFullYear()}/${pad(date.getMonth() + 1)}/${pad(date.getDate())} ` +
               `${pad(date.getHours())}:${pad(date.getMinutes())}`;
      },
      // 格式化日期部分
      formatDate(dateValue) {
        if (!dateValue) return '';
        const date = new Date(dateValue);
        const pad = n => n.toString().padStart(2, '0');
        return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
      },
      // 格式化时间部分
      formatTime(dateValue) {
        if (!dateValue) return '';
        const date = new Date(dateValue);
        const pad = n => n.toString().padStart(2, '0');
        return `${pad(date.getHours())}:${pad(date.getMinutes())}`;
      },
      // 触发搜索按钮
      handleSearch() {
          this.loading();
      },
      // 删除操作
      handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    this.$message.success('删除成功');
                    this.tableData.splice(index, 1);
                })
      },
      // 编辑操作
      handleEdit(row) {
        this.form = row;
        this.editVisible = true;
      },
      // 取消编辑
      cancelEdit() {
        // 失去当前聚焦
        document.activeElement && document.activeElement.blur();
      
        this.editVisible = false;
      },
      // 保存编辑
      saveEdit() {
        this.editVisible = false;
        requests.post("/participants/edit", this.form)
          .then(res => {
            this.$message.success(res);
            this.loading();
          })
      },
      //选择导出类型
      handleExport(){
        this.exportVisible = true
      },
      // 取消导出
      cancelExport() {
        // 失去当前聚焦
        document.activeElement && document.activeElement.blur();
      
        this.exportVisible = false;
      },
      //导出
      saveExport() {
        this.$refs.exportForm.validate((valid) => {
          if (valid) {
            // 提交逻辑
            this.exportVisible = false;
            this.exportToExcel(this.form.conferenceId)
          }
        });
      },
      // 分页导航
      handlePageChange(val) {
          this.query.pageIndex = val
          this.loading()
      },
      //导出
      exportToExcel(id) {
        requests.get("/participants/exportUserInfor", {
          conferenceId: id
        }).then(res => {
          const parseDateValue = (value) => {
            if (!value) return null;
            let date;
            if (typeof value === 'number') {
              date = new Date(value < 1e12 ? value * 1000 : value);
            } else if (typeof value === 'string') {
              const num = Number(value);
              if (!isNaN(num) && /^\d+$/.test(value.trim())) {
                date = new Date(num < 1e12 ? num * 1000 : num);
              } else {
                const parsed = Date.parse(value);
                if (isNaN(parsed)) return null;
                date = new Date(parsed);
              }
            } else {
              return null;
            }
            if (isNaN(date.getTime()) || date.getTime() <= 0) return null;
            date.setSeconds(0, 0);
            return date;
          };
        
          const safe = function(v) {
            return (v !== undefined && v !== null) ? v : '';
          };
        
          // 👇 内嵌 formatUserType 函数
          const formatUserType = (typeId) => {
            const match = (this.userType || []).find(item => item.typeId === typeId);
            return match ? match.typeName : typeId;
          };
          
          // 👇 内嵌 formatTransportType 函数
          const formatTransportType = (transportType) => {
            const transportTypeMap = {
              'plane': '飞机',
              'train': '火车', 
              'bus': '汽车',
              'car': '自驾'
            };
            return transportTypeMap[transportType] || transportType;
          };
        
          const exportData = Array.isArray(res) && res.length > 0
            ? res.map((row) => {
                if (!row) return {};
                const dateObj = parseDateValue(row.arrivalTime);
                return {
                  // 标识: String(safe(row.participantId)),
                  姓名: safe(row.fullName),
                  人员类型: formatUserType(row.typeId), // ✅ 使用内部函数
                  所属学校: String(safe(row.affiliation)),
                  性别: row.gender === 1 ? '女' : row.gender === 0 ? '男' : '',
                  手机号: safe(row.phoneNumber),
                  省份: safe(row.province),
                  身份证号: safe(row.idCardNumber),
                  交通类型: formatTransportType(row.transportType),
                  航班车次号: safe(row.flightTrainNumber),
                  到达时间: dateObj || '',
                  到站地点: safe(row.arrivalLocation),
                  是否缴费: row.hasPaidConferenceFee === 1 ? '是' : '否',
                  是否签到: row.signedIn === 1 ? '是' : '否',
                  '8月15日晚餐': row.needsPreDinner === 1 ? '是' : '否',
                  '8月16日中餐': row.needsLunch === 1 ? '是' : '否',
                  '8月16日晚餐': row.needsDinner === 1 ? '是' : '否',
                  备注: String(safe(row.notes))
                }; 

              })
            : [{
                // 标识: '',
                姓名: '',
                人员类型: '',
                所属学校: '',
                性别: '',
                手机号: '',
                省份: '',
                身份证号: '',
                交通类型: '',
                航班车次号: '',
                到达时间: '',
                到站地点: '',
                是否缴费: '',
                是否签到: '',
                '8月15日晚餐': '',
                '8月16日中餐': '',
                '8月16日晚餐': '',
                备注: ''
              }];
            
          const ws = XLSX.utils.json_to_sheet(exportData, { dateNF: 'yyyy/mm/dd hh:mm' });
            
          // 根据列标题内容长度设置列宽
          ws['!cols'] = [
            { wch: 10 }, // 姓名 (2字符 + 余量)
            { wch: 12 }, // 人员类型 (4字符 + 余量)
            { wch: 25 }, // 所属学校 (4字符但内容可能较长)
            { wch: 8 },  // 性别 (2字符 + 余量)
            { wch: 15 }, // 手机号 (3字符但内容11位数字)
            { wch: 12 }, // 省份 (2字符但内容可能较长)
            { wch: 20 }, // 身份证号 (4字符但内容18位)
            { wch: 10 }, // 交通类型 (4字符)
            { wch: 15 }, // 航班车次号 (5字符但内容可能较长)
            { wch: 18 }, // 到达时间 (4字符但格式为yyyy/mm/dd hh:mm)
            { wch: 15 }, // 到站地点 (4字符但内容可能较长)
            { wch: 10 }, // 是否缴费 (4字符)
            { wch: 10 }, // 是否签到 (4字符)
            { wch: 15 }, // 8月15日晚餐 (7字符)
            { wch: 15 }, // 8月16日中餐 (7字符)
            { wch: 15 }, // 8月16日晚餐 (7字符)
            { wch: 25 }  // 备注 (2字符但内容可能很长)
          ];
            
          const header = Object.keys(exportData[0] || {});
          const keys = Object.keys(ws);
            
          // 设置到达时间为日期格式
          const arrivalIndex = header.indexOf('到达时间');
          if (arrivalIndex >= 0) {
            const arrivalColLetter = String.fromCharCode(65 + arrivalIndex);
            keys.forEach((key) => {
              if (key.startsWith(arrivalColLetter) && key !== (arrivalColLetter + '1')) {
                const cell = ws[key];
                if (cell && (cell.v instanceof Date || !isNaN(Date.parse(cell.v)))) {
                  if (!(cell.v instanceof Date)) {
                    const d = new Date(cell.v);
                    d.setSeconds(0, 0);
                    cell.v = d;
                  }
                  cell.t = 'd';
                  cell.z = 'yyyy/mm/dd hh:mm';
                }
              }
            });
          }
        
          // 设置标识列为文本
          const serialIndex = header.indexOf('标识');
          if (serialIndex >= 0) {
            const serialColLetter = String.fromCharCode(65 + serialIndex);
            keys.forEach((key) => {
              if (key.startsWith(serialColLetter) && key !== (serialColLetter + '1')) {
                const cell = ws[key];
                if (cell) {
                  cell.t = 's';
                  cell.z = '@';
                }
              }
            });
          }
        
          const wb = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(wb, ws, '用户数据');
          XLSX.writeFile(wb, '用户列表.xlsx');
        })
      },
      //导入
      importFromExcel(e) {
        const file = e.target.files[0];
        if (!file) return;
      
        const reader = new FileReader();
        reader.onload = (event) => {
          const data = new Uint8Array(event.target.result);
          const workbook = XLSX.read(data, { type: 'array' });
        
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
        
          // raw: false 让 Excel 时间单元格转成字符串
          const excelData = XLSX.utils.sheet_to_json(worksheet, { raw: false });
        
          // 过滤掉空行（所有字段为 null/undefined 或空字符串）
          const filteredData = excelData.filter(row => {
            return Object.values(row).some(val => val !== null && val !== undefined && String(val).trim() !== '');
          });
        
          if (!filteredData || filteredData.length === 0) {
            this.$message.warning('Excel 内容为空或无有效数据，无法导入');
            this.$refs.excelInput.value = '';
            return;
          }
        
          // 通用解析函数：将类似 "2025/06/13 12:30:50" 或 "2025-06-13 12:30:50" 解析成 JS Date
          const parseExcelDate = (str) => {
            if (!str || typeof str !== 'string') return null;
            let s = str.trim().replace(/\//g, '-').replace(/\.0+$/, '');
            let timestamp = Date.parse(s);
            if (isNaN(timestamp)) {
              const parts = s.split(' ');
              if (parts.length === 2) {
                timestamp = Date.parse(parts[0] + 'T' + parts[1]);
              }
            }
            if (isNaN(timestamp)) {
              console.warn('无法解析到达时间字符串:', str);
              return null;
            }
            const date = new Date(timestamp);
            return isNaN(date.getTime()) ? null : date;
          };
        
          // 映射并校验
          const mappedData = [];
          const invalidRows = [];
          filteredData.forEach((row, idx) => {
            // 解析 participantId 为数字
            const pid = row['标识'];
            const participantId = Number(pid);
            if (isNaN(participantId)) {
              console.warn(`第 ${idx + 2} 行 “标识”无法转为数字:`, pid);
            }
          
            // 解析到达时间
            const timeStr = row['到达时间'];
            let dateObj = parseExcelDate(timeStr);
            if (dateObj) {
              // 截断到分钟：秒和毫秒置零
              dateObj.setSeconds(0, 0);
            }
          
            // 方案 A：发送 ISO 字符串（UTC），秒已为 00
            const arrivalISO = dateObj ? dateObj.toISOString() : null;
            // 方案 B：发送本地 “yyyy-MM-dd HH:mm” 格式
            let arrivalLocalMinute = null;
            if (dateObj) {
              const pad = n => n.toString().padStart(2, '0');
              const y = dateObj.getFullYear();
              const M = pad(dateObj.getMonth() + 1);
              const d = pad(dateObj.getDate());
              const h = pad(dateObj.getHours());
              const m = pad(dateObj.getMinutes());
              arrivalLocalMinute = `${y}-${M}-${d} ${h}:${m}`;
            }
            // 方案 C：发送本地 “yyyy-MM-dd HH:mm:00”
            let arrivalLocalWithSec = null;
            if (dateObj) {
              const pad = n => n.toString().padStart(2, '0');
              const y = dateObj.getFullYear();
              const M = pad(dateObj.getMonth() + 1);
              const d = pad(dateObj.getDate());
              const h = pad(dateObj.getHours());
              const m = pad(dateObj.getMinutes());
              arrivalLocalWithSec = `${y}-${M}-${d} ${h}:${m}:00`;
            }
          
            // 根据后端接口需求，选择一个格式赋值给 arrivalTime
            const arrivalTime = arrivalISO;
            // const arrivalTime = arrivalLocalMinute;
            // const arrivalTime = arrivalLocalWithSec;
          
            const item = {
              participantId: !isNaN(participantId) ? participantId : null,
              fullName: row['姓名'] || null,
              gender: row['性别'] === '男' ? 0 : row['性别'] === '女' ? 1 : null,
              phoneNumber: row['手机号'] || null,
              province: row['省份'] || null,
              idCardNumber: row['身份证号'] || null,
              transportType: row['交通类型'] || null,
              flightTrainNumber: row['航班车次号'] || row['航班/车次号'] || null,
              arrivalTime: arrivalTime, // 只保留到分钟
              arrivalLocation: row['到站地点'] || null,
              hasPaidConferenceFee: row['是否缴费'] === '否' ? 0 : 1,
              signedIn: row['是否签到'] === '否' ? 0 : 1,
              notes: row['备注'] || null
            };
            
            // 示例：把 participantId 和 arrivalTime 作为必填校验；如需更多字段校验，可在此扩展
            if (item.participantId == null || item.arrivalTime == null) {
              invalidRows.push({ rowIndex: idx + 2, data: row });
            } else {
              mappedData.push(item);
            }
          });
        
          if (mappedData.length === 0) {
            this.$message.warning('所有行均不符合导入要求（缺少必要字段），请检查后再导入');
            this.$refs.excelInput.value = '';
            console.warn('无可提交数据，以下行无效：', invalidRows);
            return;
          }
          if (invalidRows.length > 0) {
            this.$message.warning(`有 ${invalidRows.length} 行缺少必要字段，已跳过这些行，剩余 ${mappedData.length} 条数据将被导入`);
            console.warn('跳过的无效行：', invalidRows);
          }
        
          // 发送给后端
          requests.post('/participants/importUserInfor', mappedData)
            .then(response => {
              this.$message.success(response);
              this.loading();
            })
          
          this.$refs.excelInput.value = '';
        };
      
        reader.readAsArrayBuffer(file);
      },
      formatUserType(row) {
        const match = this.userType.find(item => item.typeId === row.typeId);
        return match ? match.typeName : row.typeId;
      },
      // 格式化交通类型
      formatTransportType(row, column, cellValue) {
        const transportTypeMap = {
          'plane': '飞机',
          'train': '火车', 
          'bus': '汽车',
          'car': '自驾'
        };
        return transportTypeMap[cellValue] || cellValue;
      },
      // 住宿管理
      handleEditLodging(row) {
        this.lodgingForm = { ...row };
        this.editLodgingVisible = true;
        // 获取该用户的住宿记录
        this.loadUserLodgingRecords(row.participantId);
      },
      // 取消住宿管理
      cancelEditLogding() {
        // 失去当前聚焦
        document.activeElement && document.activeElement.blur();
        
        // 清空住宿记录
        this.userLodgingRecords = [];
        this.editLodgingVisible = false;
      },
      saveEditLogding(){
        // 先校验表单
        this.$refs.lodgingForm.validate(valid => {
          if (!valid) {
            // 校验失败，不提交
            return;
          }
        
          // 校验成功，调用接口
          requests.post("/accommodationBookings/add", this.lodgingForm)
            .then(res => {
              this.$message.success(res);  // 用 success 提示更合适
              // 重新加载该用户的住宿记录
              this.loadUserLodgingRecords(this.lodgingForm.participantId);
              // 重置表单
              this.resetLodgingForm();
              this.loading();              // 刷新主表格数据
            })

        });
      },
      // 获取用户住宿记录
      loadUserLodgingRecords(participantId) {
        if (!participantId) {
          this.userLodgingRecords = [];
          return;
        }
        requests.get("/accommodationBookings/getByParticipantId", {
          participantId: participantId
        }).then(res => {
          this.userLodgingRecords = res || [];
        }).catch(err => {
          console.error('获取住宿记录失败:', err);
          this.userLodgingRecords = [];
        });
      },
      // 重置住宿表单
      resetLodgingForm() {
        this.$refs.lodgingForm.resetFields();
        // 保留用户基本信息
        const participantId = this.lodgingForm.participantId;
        const fullName = this.lodgingForm.fullName;
        this.lodgingForm = {
          participantId: participantId,
          fullName: fullName,
          hotelId: '',
          roomNumber: '',
          checkInDate: '',
          checkOutDate: ''
        };
      },
      // 删除住宿记录
      deleteLodgingRecord(record) {
        this.$confirm('确定要删除这条住宿记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          requests.delete("/accommodationBookings/delById", {
            bookingId: record.bookingId
          }).then(res => {
            this.$message.success('删除成功');
            // 重新加载住宿记录
            this.loadUserLodgingRecords(this.lodgingForm.participantId);
          }).catch(err => {
            this.$message.error('删除失败');
            console.error('删除住宿记录失败:', err);
          });
        }).catch(() => {
          // 用户取消删除
        });
      },
      // 车辆安排
      handleEditTravel(row) {
        this.travelForm = { ...row };
        this.editTravelVisible = true;
        // 获取该用户的车辆分配记录
        this.loadUserTravelRecords(row.participantId);
      },
      // 取消车辆安排
      cancelEditTravel() {
        // 失去当前聚焦
        document.activeElement && document.activeElement.blur();
        
        // 清空车辆分配记录
        this.userTravelRecords = [];
        this.editTravelVisible = false;
      },
      saveEditTraval(){
        // 先校验表单
        this.$refs.travelForm.validate(valid => {
          if (!valid) {
            // 校验失败，不提交
            return;
          }
        
          // 校验成功，调用接口
          requests.post("/vehicleAssignment/add", this.travelForm)
            .then(res => {
              this.$message.success(res);  // 用 success 提示更合适
              // 重新加载该用户的车辆分配记录
              this.loadUserTravelRecords(this.travelForm.participantId);
              // 重置表单
              this.resetTravelForm();
              this.loading();              // 刷新主表格数据
            })
        });
      },
      // 获取用户车辆分配记录
      loadUserTravelRecords(participantId) {
        if (!participantId) {
          this.userTravelRecords = [];
          return;
        }
        requests.get("/vehicleAssignment/getByParticipantId", {
          participantId: participantId
        }).then(res => {
          this.userTravelRecords = res || [];
        }).catch(err => {
          console.error('获取车辆分配记录失败:', err);
          this.userTravelRecords = [];
        });
      },
      // 重置车辆分配表单
      resetTravelForm() {
        this.$refs.travelForm.resetFields();
        // 保留用户基本信息
        const participantId = this.travelForm.participantId;
        const fullName = this.travelForm.fullName;
        this.travelForm = {
          participantId: participantId,
          fullName: fullName,
          conferenceId: '',
          vehicleId: '',
          assignmentType: ''
        };
      },
      // 删除车辆分配记录
      deleteTravelRecord(record) {
        this.$confirm('确定要删除这条车辆分配记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          requests.delete("/vehicleAssignment/delById", {
            assignmentId: record.assignmentId
          }).then(res => {
            this.$message.success('删除成功');
            // 重新加载车辆分配记录
            this.loadUserTravelRecords(this.travelForm.participantId);
          }).catch(err => {
            this.$message.error('删除失败');
            console.error('删除车辆分配记录失败:', err);
          });
        }).catch(() => {
          // 用户取消删除
        });
      }
    }
}
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
